import * as authApi from '../../api/auth'

const state = {
  // 认证状态
  isAuthenticated: false,
  // 访问令牌
  token: '',
  // 刷新令牌
  refreshToken: '',
  // 用户信息
  userInfo: null,
  // 登录加载状态
  loginLoading: false
}

const mutations = {
  // 设置认证状态
  SET_AUTHENTICATED(state, status) {
    state.isAuthenticated = status
  },
  
  // 设置令牌
  SET_TOKEN(state, { accessToken, refreshToken }) {
    state.token = accessToken
    state.refreshToken = refreshToken
    state.isAuthenticated = !!accessToken
    
    // 存储到本地
    if (accessToken) {
      uni.setStorageSync('token', accessToken)
      uni.setStorageSync('refreshToken', refreshToken)
    } else {
      uni.removeStorageSync('token')
      uni.removeStorageSync('refreshToken')
    }
  },
  
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    console.log('SET_USER_INFO mutation:', userInfo)
    state.userInfo = userInfo
    
    // 存储到本地
    if (userInfo) {
      uni.setStorageSync('userInfo', userInfo)
      console.log('用户信息已保存到本地存储')
    } else {
      uni.removeStorageSync('userInfo')
    }
  },
  
  // 设置登录加载状态
  SET_LOGIN_LOADING(state, loading) {
    state.loginLoading = loading
  },
  
  // 清除认证信息
  CLEAR_AUTH(state) {
    state.isAuthenticated = false
    state.token = ''
    state.refreshToken = ''
    state.userInfo = null
    
    // 清除本地存储
    uni.removeStorageSync('token')
    uni.removeStorageSync('refreshToken')
    uni.removeStorageSync('userInfo')
  }
}

const actions = {
  // 微信登录
  async wechatLogin({ commit }, { code, userInfo }) {
    try {
      commit('SET_LOGIN_LOADING', true)
      
      const platform = 'miniprogram'
      const response = await authApi.wechatLogin({
        code,
        userInfo,
        platform
      })
      
      console.log('API响应:', response)
      console.log('用户信息:', response.data.user)
      console.log('用户角色:', response.data.user?.role)
      
      // 设置认证信息 - 适配后端返回的token格式
      commit('SET_TOKEN', {
        accessToken: response.data.token, // 后端返回的是token字段
        refreshToken: response.data.refreshToken || response.data.token // 如果没有refreshToken，使用token
      })
      
      commit('SET_USER_INFO', response.data.user)
      
      console.log('Store中的用户信息:', this.state.userInfo)
      
      return response.data
    } catch (error) {
      console.error('微信登录失败:', error)
      throw error
    } finally {
      commit('SET_LOGIN_LOADING', false)
    }
  },
  
  // 短信登录
  async smsLogin({ commit }, { phone, code }) {
    try {
      commit('SET_LOGIN_LOADING', true)
      
      const platform = 'h5'
      const response = await authApi.smsLogin({
        phone,
        code,
        platform
      })
      
      // 设置认证信息
      commit('SET_TOKEN', {
        accessToken: response.data.accessToken,
        refreshToken: response.data.refreshToken
      })
      
      commit('SET_USER_INFO', response.data.user)
      
      return response.data
    } catch (error) {
      console.error('短信登录失败:', error)
      throw error
    } finally {
      commit('SET_LOGIN_LOADING', false)
    }
  },
  
  // 发送短信验证码
  async sendSmsCode({ commit }, phone) {
    try {
      const response = await authApi.sendSmsCode({ phone })
      return response
    } catch (error) {
      console.error('发送验证码失败:', error)
      throw error
    }
  },
  
  // 刷新令牌
  async refreshToken({ commit, state }) {
    try {
      if (!state.refreshToken) {
        throw new Error('没有刷新令牌')
      }
      
      const response = await authApi.refreshToken({
        refreshToken: state.refreshToken
      })
      
      // 更新令牌
      commit('SET_TOKEN', {
        accessToken: response.data.accessToken,
        refreshToken: response.data.refreshToken
      })
      
      return response.data
    } catch (error) {
      console.error('刷新令牌失败:', error)
      // 刷新失败，清除认证信息
      commit('CLEAR_AUTH')
      throw error
    }
  },
  
  // 登出
  async logout({ commit }) {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('登出失败:', error)
      // 即使登出接口失败，也要清除本地认证信息
    } finally {
      commit('CLEAR_AUTH')
    }
  },
  
  // 绑定手机号
  async bindPhone({ commit }, { phone, code }) {
    try {
      const response = await authApi.bindPhone({ phone, code })
      
      // 重新获取用户信息
      await this.dispatch('auth/getUserProfile')
      
      return response
    } catch (error) {
      console.error('绑定手机号失败:', error)
      throw error
    }
  },
  
  // 绑定微信账号
  async bindWechat({ commit }, { code, userInfo }) {
    try {
      const response = await authApi.bindWechat({ code, userInfo })
      
      // 重新获取用户信息
      await this.dispatch('auth/getUserProfile')
      
      return response
    } catch (error) {
      console.error('绑定微信失败:', error)
      throw error
    }
  },
  
  // 获取用户信息
  async getUserProfile({ commit }) {
    try {
      const response = await authApi.getUserProfile()
      commit('SET_USER_INFO', response.data)
      return response.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  },
  
  // 验证令牌
  async verifyToken({ commit, state }) {
    try {
      if (!state.token) {
        return false
      }
      
      await authApi.verifyToken()
      return true
    } catch (error) {
      console.error('令牌验证失败:', error)
      commit('CLEAR_AUTH')
      return false
    }
  },
  
  // 初始化认证状态
  initAuth({ commit }) {
    try {
      const token = uni.getStorageSync('token')
      const refreshToken = uni.getStorageSync('refreshToken')
      const userInfo = uni.getStorageSync('userInfo')
      
      console.log('初始化认证状态:', { token: !!token, refreshToken: !!refreshToken, userInfo: !!userInfo })
      
      if (token) {
        commit('SET_TOKEN', {
          accessToken: token,
          refreshToken: refreshToken || token // 如果没有refreshToken，使用token
        })
        
        // 设置认证状态为true
        commit('SET_AUTHENTICATED', true)
      }
      
      if (userInfo) {
        commit('SET_USER_INFO', userInfo)
      }
      
      console.log('认证状态初始化完成:', { 
        isAuthenticated: !!token, 
        hasUserInfo: !!userInfo,
        userId: userInfo?.id 
      })
    } catch (error) {
      console.error('初始化认证状态失败:', error)
      commit('CLEAR_AUTH')
    }
  },

  // 同步用户数据
  async syncUserData({ commit }) {
    try {
      const response = await authApi.syncUserData()
      
      // 更新本地用户信息
      if (response.data && response.data.data) {
        commit('SET_USER_INFO', response.data.data)
      }
      
      return response
    } catch (error) {
      console.error('同步用户数据失败:', error)
      throw error
    }
  },

  // 检查同步状态
  async checkSyncStatus() {
    try {
      return await authApi.checkSyncStatus()
    } catch (error) {
      console.error('检查同步状态失败:', error)
      throw error
    }
  },

  // 强制同步数据
  async forceSyncData({ commit }) {
    try {
      const response = await authApi.forceSyncData()
      
      // 更新本地用户信息
      if (response.data && response.data.data) {
        commit('SET_USER_INFO', response.data.data)
      }
      
      return response
    } catch (error) {
      console.error('强制同步数据失败:', error)
      throw error
    }
  },

  // 获取账户绑定状态
  async getBindingStatus() {
    try {
      return await authApi.getBindingStatus()
    } catch (error) {
      console.error('获取绑定状态失败:', error)
      throw error
    }
  },

  // 获取跨端状态
  async getCrossPlatformState() {
    try {
      return await authApi.getCrossPlatformState()
    } catch (error) {
      console.error('获取跨端状态失败:', error)
      throw error
    }
  },

  // 同步跨端状态
  async syncCrossPlatformState({ commit }) {
    try {
      const response = await authApi.syncCrossPlatformState()
      
      // 更新本地状态
      if (response.data && response.data.userState) {
        commit('SET_USER_INFO', {
          ...this.state.userInfo,
          ...response.data.userState
        })
      }
      
      return response
    } catch (error) {
      console.error('同步跨端状态失败:', error)
      throw error
    }
  },

  // 验证数据一致性
  async validateDataConsistency({ dispatch }) {
    try {
      const response = await authApi.validateDataConsistency()
      
      // 如果数据不一致，自动同步
      if (response.data && !response.data.isConsistent) {
        await dispatch('forceSyncData')
      }
      
      return response
    } catch (error) {
      console.error('验证数据一致性失败:', error)
      throw error
    }
  }
}

const getters = {
  // 是否已登录
  isLoggedIn: state => state.isAuthenticated && !!state.token,
  
  // 用户ID
  userId: state => state.userInfo?.id,
  
  // 用户昵称
  nickname: state => state.userInfo?.nickname,
  
  // 用户头像
  avatar: state => state.userInfo?.avatar || state.userInfo?.avatar_url,
  
  // 用户手机号
  phone: state => state.userInfo?.phone,
  
  // 用户积分
  points: state => state.userInfo?.points || 0,
  
  // 会员等级
  memberLevel: state => state.userInfo?.member_level,
  
  // 邀请码
  inviteCode: state => state.userInfo?.invitationCode || state.userInfo?.invite_code,
  
  // 是否绑定手机号
  hasPhone: state => !!state.userInfo?.phone,
  
  // 是否绑定微信
  hasWechat: state => !!state.userInfo?.wechat_openid,
  
  // 用户角色
  userRole: state => state.userInfo?.role || 'user',
  
  // 用户状态
  userStatus: state => state.userInfo?.status || 1,
  
  // 是否为管理员
  isAdmin: state => state.userInfo?.role === 'admin'
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}